package com.weimob.mcloud.wechatwork.customer.job;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ctrip.framework.apollo.spring.annotation.ApolloJsonValue;
import com.weimob.elasticjob.annotation.ElasticJob;
import com.weimob.mcloud.wechatwork.common.utils.JsonUtil;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.channel.request.FetchCorpInfoBySuiteIdParam;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.channel.request.FetchCorpInfoBySuiteIdReq;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.channel.response.FetchCorpInfoBySuiteIdItem;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.channel.response.FetchCorpInfoBySuiteIdResp;
import com.weimob.mcloud.wechatwork.core.adapter.service.ChannelAdapterService;
import com.weimob.mcloud.wechatwork.core.entity.privatesphere.PrivateSphere;
import com.weimob.mcloud.wechatwork.core.service.privatesphere.PrivateSphereService;
import com.weimob.mcloud.wechatwork.core.service.statistic.StatisticsService;
import com.weimob.mcloud.wechatwork.core.service.statistic.request.StatisticsRequestInfo;
import com.weimob.mcloud.wechatwork.customer.domain.DataSyncSuitModel;
import com.weimob.soa.common.utils.SoaUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 统计定时任务
 * @author tao.gu02
 * @since 1.0
 */
@Slf4j
@Component
public class StatisticTaskJob {

    @ApolloJsonValue("${data.suit.white.list:[]}")
    private List<DataSyncSuitModel> dataSyncSuitModels;
    @Reference
    private StatisticsService statisticsService;
    @Autowired
    private ChannelAdapterService channelAdapterService;
    @Reference(timeout = 20000)
    private PrivateSphereService privateSphereService;

    /**
     * 企微助手产品id
     */
    @Value("${aewc.productId:203}")
    private Long aewcProductId;


    @ElasticJob(name = "syncCorpAllNumBySuiteIed", cron = "0 0 0 * * ?")
    public void syncCorpAllNumBySuiteIed(){
        Long start = System.currentTimeMillis();
        log.info("syncCorpAllNumBySuiteIed start");
       /* //白名单逻辑
        if (CollectionUtils.isEmpty(dataSyncSuitModels)) {
            log.warn("syncCorpAllNumBySuiteIed dataSyncSuitModels is empty");
            return;
        }
        List<String> whiteSuitIds = CollUtils.map(dataSyncSuitModels, DataSyncSuitModel::getSuiteId);
        List<FetchCorpInfoBySuiteIdItem> corpIdAndSuitIds = new ArrayList<>();
        for (String suiteId : whiteSuitIds) {
            try {
                getCorpIdListByFetch(1,1,1L,100,suiteId,corpIdAndSuitIds);
            }catch (Exception e){
                log.error("syncCorpAllNumBySuiteIed getCorpIdListByFetch error",e);
            }
        }

        if(CollectionUtils.isEmpty(corpIdAndSuitIds)){
            log.warn("syncCorpAllNumBySuiteIed corpIdAndSuitIds is empty");
            return;
        }
        //寻找所有符合条件的corpId
        Set<String> corpIds = new HashSet<>();
        for (FetchCorpInfoBySuiteIdItem corpInfo : corpIdAndSuitIds) {
            corpIds.add(corpInfo.getCorpId());
        }*/

        //根据私域查询corpId信息
        PrivateSphere queryPo = new PrivateSphere();
        queryPo.setStatus(1);
        queryPo.setProductId(aewcProductId);
        List<PrivateSphere> privateSpheres = SoaUtil.unpack(privateSphereService.search(queryPo));
        if(CollectionUtils.isEmpty(privateSpheres)){
            log.warn("syncCorpAllNumBySuiteIed privateSpheres is empty");
            return;
        }
        Set<String> corpIds = new HashSet<>();
        for (PrivateSphere item : privateSpheres) {
            corpIds.add(item.getCorpId());
        }
        log.info("syncCorpAllNumBySuiteIed corpIds:{}",JsonUtil.obj2Str(corpIds));

        for (String corpId : corpIds) {
            try {
               /* //明文密文的逻辑
                String finalCorpId = corpId;
                JudgeOpenCorpIdReqDTO judgeOpenCorpIdReqDTO = new JudgeOpenCorpIdReqDTO();
                judgeOpenCorpIdReqDTO.setCorpId(corpId);
                SoaResponse<Boolean, Void> judgeResp = channelAdapterService.judgeOpenCorpId(judgeOpenCorpIdReqDTO);
                if(judgeResp!=null && judgeResp.getResponseVo()){
                    //密文换明文
                    GetCorpIdReqDTO getCorpIdReqDTO = new GetCorpIdReqDTO();
                    getCorpIdReqDTO.setOpenCorpId(corpId);
                    SoaResponse<GetCorpIdRespDTO, Void> getCorpIdRespDTO = channelAdapterService.getCorpid(getCorpIdReqDTO);
                    if(getCorpIdRespDTO!= null && getCorpIdRespDTO.getResponseVo()!=null){
                        finalCorpId = getCorpIdRespDTO.getResponseVo().getCorpId();
                    }
                }
                if(finalCorpId == null){
                    //未安装代自建，换取失败，不做统计
                    log.info("syncCorpAllNumBySuiteIed 未安装代自建 corpId:{}",corpId);
                    continue;
                }*/

                StatisticsRequestInfo statisticsRequestInfo = new StatisticsRequestInfo();
                PrivateSphere privateSphere = new PrivateSphere();
                privateSphere.setCorpId(corpId);
                statisticsRequestInfo.setPrivateSphere(privateSphere);
                statisticsService.syncCorpidStatistic(statisticsRequestInfo);
                Thread.sleep(200);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                log.error("syncCorpAllNumBySuiteIed syncCorpidStatistic,InterruptedException e", e);
            } catch (Exception e) {
                log.error("syncCorpAllNumBySuiteIed syncCorpidStatistic corpId:{} error", corpId, e);
            }
        }

        Long end = System.currentTimeMillis();
        log.info("syncCorpAllNumBySuiteIed end ,cost {}",end-start);
    }

    //获取企微suitId下所有的corpId
    public void getCorpIdListByFetch(int dbNo, int tableNo, long scrollId, int size,String suiteId,List<FetchCorpInfoBySuiteIdItem> result){
        FetchCorpInfoBySuiteIdReq req = new FetchCorpInfoBySuiteIdReq();
        FetchCorpInfoBySuiteIdParam param = new FetchCorpInfoBySuiteIdParam();
        param.setSuiteId(suiteId);
        req.setRequestParameter(param);
        req.setDbNo(dbNo);
        req.setTableNo(tableNo);
        req.setScrollId(scrollId);
        req.setSize(size);
        log.info("channelAdapterService_fetchCorpInfoBySuiteId,request:{}", JsonUtil.obj2Str(req));
        FetchCorpInfoBySuiteIdResp unpack = SoaUtil.unpack(channelAdapterService.fetchCorpInfoBySuiteId(req));
        log.info("channelAdapterService_fetchCorpInfoBySuiteId,response:{}", JsonUtil.obj2Str(unpack));
        if(CollectionUtils.isEmpty(unpack.getItems())){
            return;
        }
        result.addAll(unpack.getItems());
        getCorpIdListByFetch(unpack.getDbNo(),unpack.getTableNo(),unpack.getScrollId(),size,suiteId,result);
    }

}
